﻿using System;
using System.Globalization;
using Balloonerds.Algebra;

namespace RayTracer
{
    public class Sphere : Thing
    {
        public Vector Center { get; set; }
        public double Radius { get; set; }

        public override Vector GetSurfaceNormal(Vector point)
        {
            return (point - Center).Normalized;
        }
        public override Intersection GetIntersection(Ray ray)
        {
            Intersection intersection = null;

            var co = Center - ray.Origin;
            var v = co * ray.Direction;
            if (v > 0)
            {
                var discriminant = v * v - co * co + Radius * Radius;
                if (discriminant > 0)
                {
                    var distance = v - Math.Sqrt(discriminant);
                    var point = ray.ProjectPoint(distance);

                    intersection = new Intersection(this, ray, point, distance);
                }
            }
            return intersection;
        }

        public override Thing Translate(Vector position)
        {
            Center += position;

            return base.Translate(position);
        }
        public override Thing RotateX(double radians)
        {
            Center = Center.RotateX(radians);

            return base.RotateX(radians);
        }
        public override Thing RotateY(double radians)
        {
            Center = Center.RotateY(radians);

            return base.RotateY(radians);
        }
        public override Thing RotateZ(double radians)
        {
            Center = Center.RotateZ(radians);

            return base.RotateZ(radians);
        }

        public override string ToString()
        {
            return string.Format(NumberFormatInfo.InvariantInfo, "Sphere:C{0};R{1:0.000}", Center, Radius);
        }
    }
}
